package modelo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public abstract class ModeloBD {
	
	//private final String driver="com.mysql.jdbc.Driver";
	private final String driver="org.postgresql.Driver";
	private final String bd="BD4-4";
	//private final String url="jdbc:mysql://localhost/" + bd;
	private final String url="jdbc:postgresql://localhost/" + bd;
	private final String usr="postgres";
	private final String clave="12345";
	private Connection conn=null;

	protected final void abrirConexion(){
		try{
			Class.forName(driver);
			conn=DriverManager.getConnection(url,usr,clave);
			conn.setAutoCommit(false);
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}catch (SQLException e){
			e.printStackTrace();
		}
	}

	protected final void cerrarConexion(){
		if(conn!=null)
			try {
				conn.setAutoCommit(true);//guarda los cambios pendientes
				conn .close() ;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		conn=null;
	}

	protected final ResultSet cargarSGenerico(String sql){
		
		Statement stm=null;
		ResultSet rs=null;
		if(conn!=null)
			try {
				stm=conn.createStatement();
				rs=stm.executeQuery(sql);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		return rs;
	}
	
	protected final ResultSet cargarSGenerico2(String sql, ResultSet rs){
		Statement stm=null;		
		if(conn!=null)
			try {
				stm=conn.createStatement();
				rs=stm.executeQuery(sql);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		return rs;
	}

	protected final boolean cargarIUDGenerico (String sql){
		boolean sw=false;
		Statement stm=null;
		if(conn!=null)
			try {
				stm=conn.createStatement();
				if(stm.executeUpdate(sql)>0)
					sw=true;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		return sw;
	}
}